<script setup>
import { ref, reactive, onMounted, watch, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fileApi,api } from '@/service/api.ts';

const { config } = defineProps({
  config: {
    type: Object,
    required: true,
  }
});
const emits = defineEmits(['change']);

const Rt = reactive({
  filelist: (config.value || []).map(i => { return { oldURL: i.url, url: api + i.url }}),
  canShowRemoveDialog: true,/* 删除弹窗标志，上传不符合格式的文件会触发beforeRemove，此时不弹窗 */
  previewUrl: '',
  previewVisible: false,
});
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/'); // 检查文件类型是否为图片
  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    Rt.canShowRemoveDialog = false; // 禁止显示删除弹窗
    return false;
  }
  return true; // 返回 true 表示允许上传，返回 false 表示禁止上传
}
const handleFileUpload = (option) => {
  let formData  = new FormData();
  formData.append('file', option.file);
  formData.append('ftype', '表单图片');
  formData.append('name', option.file.name);
  fileApi({
    method: 'post',
    data: formData,
  }).then(res => {
    option.onSuccess(res, option.file);
  }).catch(error => {
    option.onError(error);
  });
}
const handleSuccess = (response, file, fileList) => {
  const data = fileList.map(i => {
    return { url: i.response?.file_url || i.oldURL };
  });
  emits('change', data);
}

const handlePreview = (file) => {
  Rt.previewUrl = file.url || file.rawUrl;
  Rt.previewVisible = true;
}
const beforeRemove = (uploadFile, uploadFiles) => {
  if (Rt.canShowRemoveDialog) {
    return showConfirmDialog({
      title: '提示',
      message: `移除附件 ${uploadFile.name} ?`,
    }).then(() => {
      return true;
    }).catch(() => {
      return false
      // on cancel
    });
  } else {
    Rt.canShowRemoveDialog = true;/* 重置状态 */
    return true;
  }
}
const handleRemove = (file, uploadFiles) => {
  const data = uploadFiles.map(i => {
    return { url: i.response?.file_url || i.oldURL };
  });
  emits('change', data);
}
</script>

<template>
  <div class="box">
    <el-upload
      class="upload-demo"
      :style="{
        '--ul-gap': `${ config.gap }px`,
        '--li-width': `${ config.eWidth }px`,
        '--li-height': `${ config.eHeight }px`
      }"
      v-model:file-list="Rt.filelist"
      :limit="config.limit"
      :disabled="Rt.filelist.length >= config.limit"
      multiple
      accept="image/*"
      :before-upload="handleBeforeUpload"
      :http-request="handleFileUpload"
      :on-success="handleSuccess"
      list-type="picture-card"
      :on-preview="handlePreview"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
    >
      <div class="flex--center flex-column plus-name">
        <el-icon color="#0079FE"><Plus /></el-icon>
        选择图片
      </div>
    </el-upload>
    
    <el-dialog v-model="Rt.previewVisible" width="fit-content">
      <img w-full :src="Rt.previewUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box {
  display: block;
  width: 100%;
  .plus-name {
    color: #0079FE;
    transform: translateY(10px);
  }
}
</style>
<style scoped>
:deep(.upload-demo .el-upload-list--picture-card) {
  display: flex;
}
:deep(.upload-demo ul) {
  gap: var(--ul-gap);
}
:deep(.upload-demo li) {
  margin: 0;
  width: var(--li-width);
  height: var(--li-height);
}
:deep(.el-upload.el-upload--picture-card) {
  width: var(--li-width);
  height: var(--li-height);
}


:deep(.el-dialog .el-dialog__body) {
  display: flex;
  min-width: 400px;
  height: fit-content;
  min-height: 250px;
  justify-content: center;
  align-items: center;
}
:deep(.el-dialog .el-dialog__body img) {
  max-width: 100%;
  max-height: 100%;
}
</style>